<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="14" :xs="24" :offset="5">
                <div class="head-container">
                    <el-input
                        v-model="queryParams.categoryName"
                        placeholder="请输入叙词名称"
                        clearable
                        size="small"
                        prefix-icon="el-icon-search"
                        style="margin-bottom: 20px"
                    />
                </div>
                <div class="head-container">
                    <div style="margin:10px 5px">
                        <el-button size="mini"  type="primary" @click="setAllExpand(true)">全部展开</el-button>
                        <el-button size="mini"  type="primary" @click="setAllExpand(false)">全部折叠</el-button>
                        <el-button size="mini"  type="primary" @click="handleUncheck">取消选中</el-button>
                    </div>
                    <div style="margin:10px 5px">
                        <el-button v-hasPermi="['system:thesauriWordCategory:add']" size="mini" plain icon="el-icon-plus" type="primary" @click="handleAdd">新增</el-button>
                        <el-button v-hasPermi="['system:thesauriWordCategory:edit']" size="mini" plain icon="el-icon-edit" type="success" @click="handleUpdate">修改</el-button>
                        <el-button v-hasPermi="['system:thesauriWordCategory:remove']"  size="mini" plain icon="el-icon-delete" type="danger" @click="handleDelete">删除</el-button>
                    </div>
                    <el-tree
                        :data="thesauriWordCategoryListTree"
                        :props="defaultProps"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        node-key="id"
                        ref="tree"
                        highlight-current
                        @node-click="handleNodeClick"
                    />
                </div>
            </el-col>
        </el-row>


        <!-- 添加或修改叙词分类对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="auto">
                <el-form-item label="叙词名称" prop="categoryName">
                    <el-input v-model="form.categoryName" placeholder="请输入叙词名称"/>
                </el-form-item>
                <el-form-item label="叙词标识" prop="categorySid">
                    <el-input v-model="form.categorySid" placeholder="请输入叙词标识"/>
                </el-form-item>
                <el-form-item label="父节点" prop="parentId">
                    <el-input v-model="form.parentName" placeholder="请选择父节点" disabled/>
                </el-form-item>
                <el-form-item label="所属叙词表" prop="thesauriWordModuleId">
                    <el-select v-model="form.thesauriWordModuleId" placeholder="请选择所属叙词表" disabled>
                        <el-option
                            v-for="item in thesauriWordModuleList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        listThesauriWordCategory,
        getThesauriWordCategory,
        delThesauriWordCategory,
        addThesauriWordCategory,
        updateThesauriWordCategory,
        exportThesauriWordCategory
    } from "@/api/system/thesauriWordCategory";

    import {
        listThesauriWordModule,
    } from "@/api/system/thesauriWordModule";

    import toTreeData  from '@/utils/toTreeData.js';


    export default {
        name: "thesauriWordCategory",
        props: {
            thesauriWordModuleId: {
                type: Number,
                default: 0
            },
        },
        data() {
            return {
                // 遮罩层
                loading: true,
                // 导出遮罩层
                exportLoading: false,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 叙词分类表格数据
                thesauriWordCategoryList: [],
                thesauriWordCategoryListTree: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 查询参数
                queryParams: {
                    categoryName: null,
                    categorySid: null,
                    parentId: null,
                    thesauriWordModuleId: null
                },
                // 表单参数
                form: {},
                // 表单校验
                rules: {},
                thesauriWordModuleList: [],
                defaultProps: {
                    children: "children",
                    label: "label"
                },
                currentlySelected: {}
            };
        },
        watch: {
            'queryParams.categoryName': {
                handler(newName, oldName) {
                    this.$refs.tree.filter(newName);
                },
                deep: true,
            },
        },
        created() {
            this.queryParams.thesauriWordModuleId = this.thesauriWordModuleId;
            Promise.all([this.getThesauriWordModuleList()]).then(() => {
                this.getList();
            }).catch(err => {
            });
        },
        methods: {
            //获取叙词表模板
            async getThesauriWordModuleList() {
                await listThesauriWordModule({}).then(response => {
                    this.thesauriWordModuleList = response.rows.map(item => {
                        return {
                            ...item,
                            value: item.id,
                            label: item.nameZh
                        }
                    });
                });
            },
            //筛选节点
            filterNode(value, data,node) {
                if (!value) {
                    node.expanded = false;
                    return true;
                }
                return this.checkBelongToChooseNode(value, data, node);
            },
            // 判断传入的节点是不是选中节点的子节点
            checkBelongToChooseNode(value, data, node) {
                if (data.label.indexOf(value) !== -1){
                    return true;
                }
                const level = node.level;
                // 如果传入的节点本身就是一级节点就不用校验了
                if (level === 1) {
                    return false;
                }
                // 先取当前节点的父节点
                let parentData = node.parent;
                // 遍历当前节点的父节点
                let index = 0;
                while (index < level - 1) {
                    // 如果匹配到直接返回
                    if (parentData.data.label.indexOf(value) != -1) {
                        return true;
                    }
                    // 否则的话再往上一层做匹配
                    parentData = parentData.parent;
                    index ++;
                }
                // 没匹配到返回false
                return false;
            },
            // 节点单击事件
            handleNodeClick(data) {
                this.currentlySelected = data;
            },
            handleUncheck() {
                this.currentlySelected = {}
                this.$refs.tree.setCurrentKey(null);
            },
            //设置全部展开和折叠。state参数为bool值
            setAllExpand(state) {
                var nodes = this.$refs.tree.store.nodesMap;
                for (var i in nodes) {
                    nodes[i].expanded = state;
                }
            },
            /** 查询叙词分类列表 */
            getList() {
                this.loading = true;
                listThesauriWordCategory(this.queryParams).then(response => {
                    this.thesauriWordCategoryList = response.rows;
                    this.thesauriWordCategoryListTree = toTreeData(response.rows,{
                        id: "id",
                        pid: "parentId",
                        label: "categoryName",
                        value: "id",
                        children: ""
                    }, "parentId", null);
                    this.total = response.total;
                    this.loading = false;
                });
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    categoryName: null,
                    categorySid: null,
                    parentId: null,
                    parentName: null,
                    thesauriWordModuleId:  this.thesauriWordModuleId
                };
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            /** 新增按钮操作 */
            handleAdd(row) {
                this.reset();
                this.open = true;
                this.title = "添加叙词分类";
                const pid = row.id;
                if(pid){
                    this.form.parentId = pid;
                }
                if(this.currentlySelected.id){
                    this.form.parentId = this.currentlySelected.id;
                    this.form.parentName = this.currentlySelected.label;
                }else{
                    this.form.parentId = 0;
                    this.form.parentName = "根目录";
                }
            },
            /** 修改按钮操作 */
            handleUpdate() {
                this.reset();
                if(this.currentlySelected.id){
                    getThesauriWordCategory(this.currentlySelected.id).then(response => {
                        this.form = response.data;
                        this.form.parentName = "根目录";
                        if(this.form.parentId != 0){
                            this.form.parentName = this.thesauriWordCategoryList.filter(x=>x.id == this.form.parentId)[0]["categoryName"];
                        }
                        this.open = true;
                        this.title = "修改叙词分类";
                    });
                }else{
                    this.$modal.msgWarning("请选择需要修改的数据");
                }
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.id != null) {
                            updateThesauriWordCategory(this.form).then(response => {
                                this.$modal.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            });
                        } else {
                            addThesauriWordCategory(this.form).then(response => {
                                this.$modal.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            });
                        }
                        this.currentlySelected= {};
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete() {
                if(this.currentlySelected.id){
                    const ids = this.currentlySelected.id;
                    this.$modal.confirm('是否确认选中的数据项 （若选中节点为父节点其子节点也会被删除）？').then(function () {
                        return delThesauriWordCategory(ids);
                    }).then(() => {
                        this.getList();
                        this.$modal.msgSuccess("删除成功");
                    }).catch(() => {
                    });
                }else{
                    this.$modal.msgWarning("请选择需要删除的数据");
                }
            },
        }
    };
</script>
<style>
    /*将默认背景色进行透明处理*/
    .head-container .el-tree {
        background: rgb(255 255 255) !important;
        color: #fff !important;
    }
    /*覆盖原有的字体大小*/
    .head-container .el-tree-node__label {
        font-size: 16px !important;
        color: #333;
    }
    /*当鼠标浮动时，进行颜色改变，默认的为白色*/
    .head-container .el-tree-node__content:hover {
        /*background-color: #73bda5 !important;*/
    }
    /*当选中树节点时的颜色改变，默认为白色*/
    .head-container .el-tree-node:focus>.el-tree-node__content {
        background-color: #73bdf5 !important;
    }

    .el-tree-node:focus > .el-tree-node__content {
        background-color: #73bdf5;
        color: #fff;
    }
    .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
        background-color: #73bdf5;
        color: #fff;
    }
</style>
